import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from "element-plus";
import HomeView from '../views/HomeView.vue'
import UserLogin from '../views/UserLogin.vue'
import ShopView from '../views/ShopView.vue'
import PersonView from '../views/PersonView.vue'
import PersonShell from '../views/PersonShell.vue'
import PersonCart from '../views/PersonCart.vue'
import PersonRecode from '../views/PersonRecode.vue'
import AdminLogin from '../views/AdminLogin.vue'
import ManageStaff from '../views/ManageStaff.vue'
import ManageOffer from '../views/ManageOffer.vue'
import ManageState from '../views/ManageState.vue'
import ManageCustomer from '../views/ManageCustomer.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'userhome',
      component: HomeView
    },
    {
      path: '/userlogin',
      name: 'userlogin',
      component: UserLogin
    },
    {
      path: '/usershop',
      name: 'usershop',
      component: ShopView
    },
    {
      path: '/userperson',
      name: 'userperson',
      component: PersonView
    },
    {
      path: '/usershell',
      name: 'usershell',
      component: PersonShell
    },
    {
      path: '/usercart',
      name: 'usercart',
      component: PersonCart,
    },
    {
      path: '/userrecode',
      name: 'userrecode',
      component: PersonRecode
    },
    {
      path: '/adminlogin',
      name: 'adminlogin',
      component: AdminLogin
    },
    {
      path: '/managestaff',
      name: 'managestaff',
      component: ManageStaff
    },
    {
      path: '/manageoffer',
      name: 'manageoffer',
      component: ManageOffer
    },
    {
      path: '/managestate',
      name: 'manageState',
      component: ManageState
    },
    {
      path: '/managecustomer',
      name: 'managecustomer',
      component: ManageCustomer
    }
  ]
})

router.beforeEach((to, from, next) => {
  const publicPages = ['/', '/userlogin', '/usershop', '/adminlogin'];  // 不需要身份验证的路由
  let authRequired = !publicPages.includes(to.path); // 检查即将进入的页面是否需要验证
  let loggedIn = JSON.parse(localStorage.getItem('user')); // 检测是否已登录

  if(loggedIn) {
    let loginTime = new Date(loggedIn.data.nowDate);
    let currentTime = new Date();
    let timeDifference = currentTime - loginTime;
    let towHours = 2* 60 * 60 * 1000;

    if(timeDifference > towHours) {
      localStorage.removeItem('user');
      ElMessage.error("登录超时，请重新登录");
      return next('/usershop');
    }
  }

  if (authRequired && !loggedIn) { // 如果需要验证且没有登录
    ElMessage.error("用户未登录，请进行登录");
    return next('/'); // 重定向到登录页面
  }
  next(); // 如果不需要验证，或者已经登录，就正常导航
})

export default router
